<?php

namespace Application\Controllers;

use Application\Models\BookCategory;
use Application\Models\BookKanCloud;
use Mpdf\Mpdf;
use Mpdf\Output\Destination;
use Phalcon\Mvc\Controller;

error_reporting(0);

class ApiController extends Controller
{
    use \Application\Controllers\Controller;
    public $soncat = array();

    public function kancloudAction()
    {
        $category = new BookCategory();
        $this->view->setVar('category', $category->getOptionList());
        $catlist = $category->getCategoryList();
        foreach ($catlist as &$v) {
            $v['level'] = str_repeat('&nbsp;&nbsp;&nbsp;', $v['level'] - 1);
        }
        $this->view->setVar('catlist', $catlist);
        $list = BookKanCloud::find(['order' => 'addtime asc'])->toArray();
        foreach ($list as &$value) {
            $value['title'] = mb_substr($value['title'], 0, 10, 'UTF-8');
            $value['edittime'] = date('Y-m-d H:i', strtotime($value['edittime']));
        }
        $partal = $this->view->getPartial("api/articles", $list);
        $this->view->setVar('list', $partal);
    }

    public function articlesAction()
    {
        $cid = $this->request->get('cid', null, 0);
        $this->getsoncat($cid);
        $list = BookKanCloud::find([
            'cid in ({cid:array})',
            'bind' => ['cid' => $this->soncat],
            'order' => 'addtime asc'
        ])->toArray();
        if (!$list) {
            return $this->response->setJsonContent(['status' => 1, 'info' => '']);
        }
        $articles = [];
        foreach ($list as $value) {
            $value['title'] = mb_substr($value['title'], 0, 10, 'UTF-8');
            $value['edittime'] = date('Y-m-d H:i', strtotime($value['edittime']));
            $articles [] = $value;
        }
        $partal = $this->view->getPartial("api/articles", $articles);
        return $this->response->setJsonContent(['status' => 1, 'info' => $partal]);
    }

    public function addartAction()
    {
        $html = $this->request->getPost('html');
        $markdown = $this->request->getPost('markdown');
        $title = $this->request->getPost('title');
        $author = $this->request->getPost('author');
        $url = $this->request->getPost('url');
        $catid = $this->request->getPost('catid');
        $artid = $this->request->getPost('artid');
        if (!$catid) {
            return $this->error('请为文章选择一个归属吧');
        }
        if (!$markdown) {
            return $this->error('请不要让编辑内容为空吧');
        }
        if (!$title) {
            return $this->error('请选择一个标题吧');
        }
        $data = array(
            'title' => $title,
            'cid' => $catid,
            'author' => $author,
            'url' => $url,
            'content' => $html,
            'markdown' => $markdown,
            'editor' => 0,
            'addtime' => date('Y-m-d H:i:s'),
            'edittime' => date('Y-m-d H:i:s'),
            'lock' => 0,
            'password' => '',
            'tag' => ''
        );

        $articleModel = new BookKanCloud();
        if ($artid) {
            $article = $articleModel->findFirst($artid);
            unset($data['addtime']);
            $article->assign($data);
            if ($article->save()) {
                return $this->success('修改文章成功');
            } else {
                return $this->error('修改文章失败');
            }
        } else {
            $articleModel->assign($data);
            if ($id = $articleModel->save()) {
                return $this->success($articleModel->id);
            } else {
                return $this->error('添加文章失败');
            }
        }
    }

    //删除文档
    public function delartAction()
    {
        $artid = $this->request->get('artid', null, 0);
        if (!$artid) {
            return $this->error('错误请求，请重试~');
        }
        $article = BookKanCloud::findFirst($artid);
        if ($article->delete()) {
            return $this->success('删除文章成功');
        } else {
            return $this->error('删除文章失败');
        }
    }

    //获取所有下级
    private function getsoncat($cid)
    {
        $list = BookCategory::find(['pid=' . $cid])->toArray();
        $this->soncat[] = $cid;
        foreach ($list as $value) {
            $this->getsoncat($value['id']);
        }
    }

    public function articleAction()
    {
        $artid = $this->request->get('artid', null, 0);
        if (!$artid) {
            return $this->response->setJsonContent(['status' => 0, 'info' => '参数错误']);
        }
        $info = BookKanCloud::findFirst($artid)->toArray();
        $info['markdown'] = htmlspecialchars_decode($info['markdown']);
        $info['content'] = htmlspecialchars_decode($info['content']);
        if ($info) {
            return $this->success($info);
        } else {
            return $this->error('该文章已经不存在');
        }
    }

    /**
     * 生成PDF
     *
     */
    public function makePdfAction()
    {
        set_time_limit(30);
        $catid = $this->request->get('catid');
        $catinfo = BookCategory::findFirst($catid)->toArray();
        $title = iconv('utf-8', 'gbk', $catinfo['name']);
        $pdfPath = "pdfs";
        $book = $pdfPath . '/' . $title . '.pdf';
        if (!is_dir($pdfPath)) {
            mkdir($pdfPath, 0777);
        }
        //测试每次都生成
//        if (file_exists($book)) {
//            return $this->success($this->url->getStatic($book));
//        }
        $list = BookKanCloud::find(['cid=' . $catid, 'order' => 'id asc'])->toArray();
        $html = $this->view->getPartial("api/makepdf", ['list' => $list, 'title' => $title]);
        //todo 处理mpdf的标点符号BUG
        $html = str_replace(
            ["（","）",'、','。','，','“','”','；','：'],
            [' (',') ',', ','. ',' ,',' "','" ','; ',': '],
            $html
        );
        if (!is_writeable($pdfPath)) {
            return $this->error($pdfPath . ' path is not writeable');
        }
        try {
            //todo 这里的配置是毛?
            $mpdf = new Mpdf([
                    'mode' => '',
                    'format' => 'A4',
                    'default_font_size' => 0,
                    'default_font' => '',
                    'margin_left' => 15,
                    'margin_right' => 15,
                    'margin_top' => 16,
                    'margin_bottom' => 16,
                    'margin_header' => 10,
                    'margin_footer' => 10,
                    'orientation' => 'P',
                ]);
            $mpdf->autoScriptToLang = true;
            $mpdf->baseScript = 1;
            $mpdf->autoVietnamese = true;
            $mpdf->autoArabic = true;
            $mpdf->autoLangToFont = true;    //自动语言选择
            $stylesheet = file_get_contents('plus/editor.md/css/editormd.min.css');
            $stylesheet .= file_get_contents('plus/editor.md/css/editormd.preview.min.css');
            $stylesheet .= file_get_contents("assets/pdf/css/bootstrap.min.css");
            //添加水印
            $mpdf->SetWatermarkText('blog.mirchen.com');            //水印内容
            $mpdf->watermark_font = 'DejaVuSansCondensed';          //水印字体
            $mpdf->showWatermarkText = false;
            $mpdf->h2bookmarks = ['H1' => 0];                  //从h1标签内读取标签
            $mpdf->WriteHTML($stylesheet, 1);
            $mpdf->WriteHTML($html);                                //写入内容
            $mpdf->Output($book, Destination::FILE);
            return $this->success($this->url->getStatic($book));
        } catch (\Exception $exception) {
            $errmsg = $exception->getMessage();
            if(strpos($errmsg,'Invalid size representation') !== false) {
                $errmsg = 'css样式错误无法兼容:'.$errmsg;
            }
            return $this->error($errmsg);
        }
    }

    public function cateditAction()
    {
        $catid = (int)$this->request->get('id');
        $imgurl = $this->request->get('imgurl');
        if (!$catid || !$imgurl) {
            return $this->error("参数错误");
        }
        $catinfo = BookCategory::findFirst($catid);
        if (!$catinfo) {
            return $this->error("不存在catinfo");
        }
        $catinfo->imgurl = $imgurl;
        if ($catinfo->save()) {
            return $this->success('成功');
        } else {
            return $this->error('更新失败');
        }
    }

    public function addcatAction()
    {
        $catname = $this->request->get('catname');
        $pid = $this->request->get('pid');

        if (!$catname || !$pid) {
            return $this->error('参数错误');
        }

        $cat = new BookCategory();
        $cat->name = $catname;
        $cat->pid = $pid;
        $cat->sort = 10;
        $cat->url = '';
        $cat->description = '';
        $cat->keywords = '';
        $cat->imgurl = '';
        if ($cat->save()) {
            return $this->success('添加分类成功');
        }
        return $this->error('添加分类失败');
    }

    public function delcatAction()
    {
        $id = (int)$this->request->get('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $cat = BookCategory::findFirst($id);
        if (!$cat) {
            return $this->error('分类不存在');
        }
        //查看文章
        if (BookKanCloud::findFirst(['cid=' . $id])) {
            return $this->error('分类下还有文档无法删除');
        }
        if (BookCategory::findFirst(['pid=' . $id])) {
            return $this->error('还有下级分类，无法删除');
        }
        if ($cat->delete()) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
}